#pragma once

#include <iostream>
#include <unordered_map>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
// 每一个用户对应的信息
class User
{
public:
    User(const std::string &ip, const uint16_t &port) : _ip(ip), _port(port)
    {
    }

public:
    std::string _ip;
    uint16_t _port;
};

// 管理在线用户
class OnlineUser
{
public:
    OnlineUser() {}
    ~OnlineUser() {}

    void addUser(const std::string &ip, const uint16_t &port)
    {
        std::string id = ip + "-" + std::to_string(port);
        _users.insert(std::make_pair(id, User(ip, port)));
    }

    void delUser(const std::string &ip, const uint16_t &port)
    {
        std::string id = ip + "-" + std::to_string(port);
        _users.erase(id);
    }

    bool isOnline(const std::string &ip, const uint16_t &port)
    {
        std::string id = ip + "-" + std::to_string(port);
        return _users.find(id) == _users.end() ? false : true;
    }

    // 这里的参数ip和port是指发消息的是谁
    void broadcastMessage(int sockfd, const std::string &ip, const uint16_t &port, const std::string message)
    {
        // 向每一个在线用户转发消息
        for (auto &user : _users)
        {
            struct sockaddr_in server_send;
            server_send.sin_family = AF_INET;
            server_send.sin_port = htons(user.second._port);
            server_send.sin_addr.s_addr = inet_addr(user.second._ip.c_str());
            std::string s = ip + "-" + std::to_string(port) + "# ";
            s += message;
            sendto(sockfd, s.c_str(), s.size(), 0, (struct sockaddr *)&server_send, sizeof(server_send));
        }
    }

private:
    std::unordered_map<std::string, User> _users;
};